//
//  QUTableView.m
//  FaceCard
//
//  Created by 瞿伦平 on 2017/6/23.
//  Copyright © 2017年 瞿伦平. All rights reserved.
//

#import "QUTableView.h"

@implementation QUTableCustomView

- (id)init
{
    
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        
        float padding = 10;
        UIView *superView = self;
        
        UIImageView *imgView = [superView newUIImageViewWithImg:IMG(@"bj.png")];
        imgView.layer.cornerRadius = 10;
        imgView.layer.masksToBounds = YES;
        self.msgLable = [superView newUILableWithText:@"" textColor:[UIColor colorWithWhite:0.2 alpha:1] font:[UIFont systemFontOfSize:16]];
        self.msgLable.textAlignment = NSTextAlignmentCenter;
        self.msgLable.numberOfLines = 0;
        
        self.desLable = [superView newUILableWithText:@"可重新下拉加载数据哦，亲" textColor:[UIColor grayColor] font:[UIFont systemFontOfSize:14]];
        self.desLable.textAlignment = NSTextAlignmentCenter;
        self.desLable.numberOfLines = 0;
        
        [imgView makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(superView.top).offset(padding);
            //make.width.height.equalTo(40);
            make.width.equalTo(superView.width).multipliedBy(0.25);
            make.height.equalTo(imgView.width);
            make.centerX.equalTo(superView.centerX);
        }];
        [self.msgLable makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imgView.bottom).offset(padding*2);
            make.left.equalTo(superView.left).offset(padding);
            make.right.equalTo(superView.right).offset(-padding);
        }];
        [self.desLable makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_msgLable.bottom).offset(padding);
            make.left.equalTo(superView.left).offset(padding);
            make.right.equalTo(superView.right).offset(-padding);
            //make.bottom.equalTo(superView.bottom).offset(-padding);
        }];
    }
    return self;
}

@end






@implementation QUTableView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.pageRow = 20;
    }
    return self;
}




-(void)setHaveHeader
{
    __weak typeof(self) weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadHeaderRefreshing];
    }];
    self.mj_header = header;
    
//    [header setTitle:@"" forState:MJRefreshStateIdle];
//    [header setTitle:@"" forState:MJRefreshStatePulling];
//    [header setTitle:@"" forState:MJRefreshStateRefreshing];
}

-(void)setHaveFooter
{
    __weak typeof(self) weakSelf = self;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadFooterRefreshing];
    }];
    footer.automaticallyRefresh = YES;  // 自动加载
    footer.refreshingTitleHidden = YES;
    footer.automaticallyHidden = YES;
    self.mj_footer = footer;
    
    self.mj_footer.hidden = YES;
    
    [self setHaveEmptyView];
}

-(void)setHaveHeaderFooter
{
    [self setHaveHeader];
    [self setHaveFooter];
}


#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

-(void)beginHeaderRereshing
{
    self.startId = kTableFirstDataNumber;
    [self.mj_header beginRefreshing];
}

-(void)loadHeaderRefreshing
{
    self.mj_footer.hidden = YES;
    if (self.startId != kTableFirstDataNumber)
        self.startId = kTableFirstDataNumber;
    self.tableIsReloading = YES;
    [self reloadEmptyDataSet];
    [self reloadTableViewDataSource];
}

-(void)loadFooterRefreshing
{
    self.startId ++;
    self.tableIsReloading = YES;
    [self reloadTableViewDataSource];
}

- (void)reloadTableViewDataSource
{
    if (self.refreshingBlock)
        self.refreshingBlock(_startId);
}

-(void)doneHeaderRereshingWithTableArr:(NSMutableArray *)tableArr addArr:(NSArray *)arr info:(APIObject*)info
{
    if (arr.count > 0) {
        [tableArr setArray:arr];
        
        if (arr.count == _pageRow)
            self.mj_footer.state = MJRefreshStateIdle;
        else
            self.mj_footer.state = MJRefreshStateNoMoreData;

    } else {
        [tableArr removeAllObjects];
        
        if (arr != nil)
            self.errMsg = info.msg!=nil ? info.msg : @"暂无数据";
        else
            self.errMsg = info.msg!=nil ? info.msg : @"网络错误";
        
        self.mj_footer.state = MJRefreshStateNoMoreData;
    }
        
    
//    if (self.mj_footer != nil) {
//        if (arr.count > 0)
//            self.mj_footer.hidden = NO;
//        else
//            self.mj_footer.hidden = YES;
//    }
    
    
    self.tableIsReloading = NO;
    
    [self reloadData];
    [self.mj_header endRefreshing];
    
    [self reloadEmptyDataSet];
}

-(void)doneFooterRereshingWithTableArr:(NSMutableArray *)tableArr addArr:(NSArray *)arr info:(APIObject*)info
{
    if (arr.count > 0) {
        [tableArr addObjectsFromArray:arr];
    } else {
        self.startId --;
        
        if (arr != nil)
            self.errMsg = @"暂无数据";
        else
            self.errMsg = info.msg!=nil ? info.msg : @"网络错误";
    }
    
    self.tableIsReloading = NO;
    [self reloadData];
    [self.mj_footer endRefreshing];
    
    if (arr.count == _pageRow)
        [self.mj_footer resetNoMoreData];
    else
        [self.mj_footer endRefreshingWithNoMoreData];
}

- (void)doneLoadingTableViewDataWithTableArr:(NSMutableArray *)tableArr addArr:(NSArray *)arr info:(APIObject*)info
{
    if (self.startId == kTableFirstDataNumber)
        [self doneHeaderRereshingWithTableArr:tableArr addArr:arr info:info];
    else
        [self doneFooterRereshingWithTableArr:tableArr addArr:arr info:info];
}



#pragma mark - DZNEmptyDataSetDelegate Methods

-(void)setHaveEmptyView
{
    self.emptyDataSetSource = self;
    self.emptyDataSetDelegate = self;
}

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
{
    return _tableIsReloading ? NO : YES;
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView
{
    return NO;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

#pragma mark - DZNEmptyDataSetSource Methods

- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
{
    if (_errMsg.length > 0) {
        QUTableCustomView *view = [[QUTableCustomView alloc] init];
        view.backgroundColor = [UIColor redColor];
        view.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
        view.msgLable.text = _errMsg;
        return view;
    }
    return nil;
}

//- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
//{
//    return IMG(@"bj.png");
//}
//
//- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
//{
//    NSString *text = nil;
//    UIFont *font = nil;
//    UIColor *textColor = nil;
//    
//    NSMutableDictionary *attributes = [NSMutableDictionary new];
//    
//
//    text = _errMsg;
//    font = [UIFont boldSystemFontOfSize:16.0];
//    textColor = [UIColor colorWithWhite:0.2 alpha:1];
//    
//    if (!text) {
//        return nil;
//    }
//    
//    if (font) [attributes setObject:font forKey:NSFontAttributeName];
//    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
//    
//    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
//}
//
//
//- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
//{
//    NSString *text = nil;
//    UIFont *font = nil;
//    UIColor *textColor = nil;
//    
//    NSMutableDictionary *attributes = [NSMutableDictionary new];
//    
//    NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
//    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
//    paragraph.alignment = NSTextAlignmentCenter;
//    
//    text = @"亲,下拉重新刷新数据";
//    font = [UIFont boldSystemFontOfSize:16.0];
//    textColor = [UIColor grayColor];
//    
//    if (!text) {
//        return nil;
//    }
//    
//    if (font) [attributes setObject:font forKey:NSFontAttributeName];
//    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
//    if (paragraph) [attributes setObject:paragraph forKey:NSParagraphStyleAttributeName];
//    
//    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
//    
//    return attributedString;
//}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
//{
//    CGFloat aa = self.frame.size.height;
//    CGFloat offset = (aa - QUTableCustomView_Height) / 3.5;
//    return -offset;
//}


#pragma mark -
#pragma mark Table view data source
- (NSInteger)qu_tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_tableIsReloading)
        return 0;
    else
        return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_tableIsReloading)
        return 44;
    else
        return 50;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell_Something";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.editing = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.font = [UIFont systemFontOfSize:12];
    }
    
    if (_tableIsReloading)
        cell.textLabel.text = @"";
    else
        cell.textLabel.text = self.errMsg;
    
    return cell;
}


@end
